import {url} from '../utils'
import {OrderBundle, KeyValueLabel, Order, OrderExtraFee, OrderItem, OrderItemType} from '@/store/modules/types/Order'
import {AxiosResponse} from 'axios'
import {Asset} from '@/store/modules/types/Asset'
import {AssetStock} from '@/store/modules/types/AssetStock'
import {Rentalable, WithId} from '@/store/modules/types/Bundle'
import _ from 'lodash'


function isExists(arr: OrderItem[], item: Rentalable) {
  if (item.type == OrderItemType.ExtraFee) {
    return arr.some((x: OrderItem) => x.name === item.name)
  } else {
    return arr.some((x: OrderItem) => x.rentalable_id === item.id && x.rentalable_type === item.type)
  }
}

function _buildOrderItem(item: Rentalable, orderId: number): OrderItem {
  let unitPrice = item.marking_price || item.marking_price_per_unit || item.unit_price
  let quantity = item.quantity || 1
  return {
    order_id: orderId,
    name: item.name,
    rentalable_id: item.id,
    rentalable_type: item.type,
    quantity: quantity,
    unit_price: unitPrice,
    amount: unitPrice * quantity,
    rental_out_at: null,
    return_at: null,
    rentalable: item
  }
}

const state = {
  order: {} as Order,
  orderBundles: [] as OrderBundle[],
  orderBundlesClone: [] as OrderBundle[],
  orderClone: {} as Order, // 用于编辑的对象
  orderItems: [] as OrderItem[],
  orderItemsClone: [] as OrderItem[], // 用于编辑的对象,
  extraPayments: [] as OrderExtraFee[],
  extraPaymentsClone: [] as OrderExtraFee[],
  orderItemsSummary: [] as OrderItem[], // 用于计算总价创造虚拟的数据表格
  orderItemsSummaryClone: [] as OrderItem[],
  customers: [] as KeyValueLabel[],
  paymentMethods: [] as KeyValueLabel[]

}


const mutations = {
  dummy(state: any) {
    // do nothing
  },
  addExtraFee(state: any, fee: OrderExtraFee) {
    if (!isExists(state.orderItemsClone, fee)) {
      state.orderItemsClone.push(_buildOrderItem(fee, state.order.id))
    }
  },
  resetClone(state: any) {
    state.orderClone = state.order
    state.orderItemsClone = state.orderItems
  },
  setActive(state: any, order: Order) {
    state.order = order
    state.orderClone = order
  },
  updateCustomers(state: any, payload: KeyValueLabel[]) {
    state.customers = payload
  },
  setOrderItems(state: any, orderItems: OrderItem[]) {
    state.orderItems = orderItems
    state.orderItemsClone = orderItems
  },
  clearOrderItems(state: any) {
    state.orderItems = []
    state.orderItemsClone = []
  },
  setOrderBundles(state: any, bundles: OrderBundle[]) {
    state.orderBundles = bundles
    state.orderBundlesClone = bundles
  },
  clearOrderBundles(state: any) {
    state.orderBundles = []
    state.orderBundlesClone = []
  },
  updatePaymentMethods(state: any, payload: KeyValueLabel[]) {
    state.paymentMethods = payload
  },
  addNewCustomer(state: any, payload: KeyValueLabel) {
    state.customers.push(payload)
  },
  addBundle(state: any, bundle: OrderBundle) {
    if (!_.some(state.orderBundlesClone, item => item.bundle_id == bundle.bundle_id)) {
      bundle.amount = 0;
      bundle.rental_out_at = null;
      bundle.return_at = null;
      state.orderBundlesClone.push(bundle)
    }
  },
  removeBundle(state: any, bundleId: string | number) {
    state.orderBundlesClone = state.orderBundlesClone.filter((item: OrderBundle) => {
      return item.id != bundleId
    })
  },
  updateBundleAmount(state: any, {id, amount}: any){
    let bundle = _.find(state.orderBundlesClone, {id: id})
    bundle.amount = amount
  },
  addAssets(state: any, { assets, assetStocks }: { assets: Asset[], assetStocks: AssetStock[] }) {
    let arr: Rentalable[] = assets.concat(assetStocks)
    arr.forEach((item: Rentalable) => {
      if (!isExists(state.orderItemsClone, item)) {
        state.orderItemsClone.push(_buildOrderItem(item, state.order.id))
      }
    })
  },
  removeAssets(state: any, items: OrderItem[]) {
    state.orderItemsClone = state.orderItemsClone.filter((item: OrderItem) => {
      return !items.some((x: OrderItem) => {
        return x === item
      })
    })
  }
}

const actions = {
  createOrUpdate(context: any) {
    let { orderClone, orderItemsClone, orderBundlesClone } = context.state
    return axios.post(url('/api/order/create-or-update'), { order: orderClone, orderItems: orderItemsClone, orderBundles: orderBundlesClone })
  },
  list(context: any, opt: any) {
    return axios.post(url('/api/order/list'), opt)
  },
  allPaymentMethods(context: any) {
    return axios.post(url('/api/order/k-v/all-payment-methods')).then((response: AxiosResponse) => {
      context.commit('updatePaymentMethods', response.data.data)
    }).catch(console.error)
  },
  allCustomers(context: any) {
    return axios.post(url('/api/customer/k-v/list-all')).then((response: AxiosResponse) => {
      context.commit('updateCustomers', response.data.data)
      // eslint-disable-next-line no-console
    }).catch(console.error)
  },
  fetchOrderItemsByOrderId(context: any, id: string | number) {
    return axios.post(url(`/api/order/order-items/${id}`)).then((response: AxiosResponse) => {
      context.commit('setOrderItems', response.data.data)
    }).catch(console.error)
  },

  fetchOrderBundlesByOrderId(context: any, id: string | number) {
    return axios.post(url(`/api/order/order-bundles/${id}`)).then((response: AxiosResponse) => {
      context.commit('setOrderBundles', response.data.data)
    }).catch(console.error)
  },
  retrieveAssets(context: any, query: string) {
    return axios.post(url('/api/order/query-assets'), { query })
  },
  lendOrderItems(context: any, payload: any) {
    let id = context.state.order.id
    return axios.post(url(`/api/order/lend/${id}`), payload)
  },
  returnOrderItems(context: any, payload: any) {
    let id = context.state.order.id
    return axios.post(url(`/api/order/return/${id}`), payload)
  },
  completeOrder(context: any) {
    let id = context.state.order.id
    return axios.post(url(`/api/order/complete/${id}`))
  },
  cancelOrder(context: any) {
    let id = context.state.order.id
    return axios.post(url(`/api/order/cancel/${id}`))
  },
  revertOrder(context: any) {
    let id = context.state.order.id
    return axios.post(url(`/api/order/revert/${id}`))
  }
}

const getters = {
  OrderItemsDataSource(state: any) {
    // let totalPrice = state.orderItems.reduce((acc: number, cur: OrderItem, index: number) => {
    //   let discount = cur.rentalable_type == OrderItemType.ExtraFee ? 1:  state.order.discount
    //   return acc = acc + (cur.unit_price * cur.quantity) * discount
    // }, 0)
    let totalPrice = parseFloat(state.order.net_amount)
    let totalBundleFee = _.sumBy(state.orderBundles, (bundle: OrderBundle) => parseFloat(bundle.amount))
    let virtualDataRow: OrderItem = {
      name: '',
      quantity: `总价 (折扣 ${state.order.discount})`,
      amount: (totalPrice - totalBundleFee).toFixed(2)
    }
    return state.orderItems.concat([virtualDataRow])
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
